package eddy.yang.wordpad;

import java.awt.*;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;
import java.awt.print.*;
import javax.print.attribute.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.undo.CannotUndoException;

public class WordPadFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	public WordPadFrame(String label) {
		super(label);

		myDeskPane = new JDesktopPane();
		myDeskPane.setOpaque(true);
		myDeskPane.setBackground(Color.gray);
		
		tabbedpane = new JTabbedPane();
		tabbedpane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		tabbedpane.setBackground(Color.gray);
		
		myparagraphDialog = new ParagraphDialog(this);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				setAlwaysOnTop(false);
				doExit();
//				TODO		if(doExit()) {
//							System.exit(0);
////						}
//						else
//							return;
			}
		});
		
		this.getContentPane().add(createToolBar(), BorderLayout.NORTH);
		this.getContentPane().add(tabbedpane, BorderLayout.CENTER);
		setJMenuBar(createMenuBar());
		new DropTarget(this, new MyDropTargetListener(this));
	}
	
	public JMenuBar createMenuBar() {
		JMenuBar menubar = new JMenuBar();
		menubar.add (createLafMenu());
		menubar.add (createFileMenu());
		menubar.add (createEditorMenu());		
		menubar.add (createColorMenu());
		menubar.add (createFontMenu());
		menubar.add (createViewMenu());
		
		
		JMenu insertMenu = new JMenu("插入");
		JMenuItem item;
		insertMenu.add(item = new JMenuItem("来自文件"));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel pane;
				if(tabbedpPaneRadio.isSelected())
					pane = (WordPadPanel) tabbedpane.getSelectedComponent();
				else {
					WordPadInternalFrame selectFrame = (WordPadInternalFrame) myDeskPane.getSelectedFrame();
					pane = selectFrame.getWordPadPanel();
				}
				pane.doInsertCommand();
			}
		});
		menubar.add(insertMenu);	
		menubar.add (createAbortMenu());	
		return menubar;
	}
	
	public JMenu createLafMenu() {
		lafmenu = new JMenu("风格");
		ButtonGroup group = new ButtonGroup();
		JRadioButtonMenuItem item;
		final String[] themes = {
				 "javax.swing.plaf.metal.MetalLookAndFeel",
				 "com.sun.java.swing.plaf.motif.MotifLookAndFeel",
				 "com.sun.java.swing.plaf.windows.WindowsLookAndFeel",
		};
		final String[] names = {
				"MetalLookAndFeel",
				"MotifLookAndFeel",
				"WindowsLookAndFeel",
		};
		
		ActionListener lafListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String lafname = themes[Integer.parseInt(e.getActionCommand())];
				try {
					UIManager.setLookAndFeel(lafname);
					SwingUtilities.updateComponentTreeUI(WordPadFrame.this);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		};
		
		for(int i = 0; i < names.length; i++) {
			lafmenu.add(item = new JRadioButtonMenuItem(names[i]));
			item.setActionCommand(i + "");
			item.addActionListener(lafListener);
			group.add(item);
			if(i == 0)
				item.setSelected(true);
		}

		return lafmenu;
	}
	
	public JMenu createFileMenu() {
		JMenu filemenu = new JMenu("文件");
		filemenu.setMnemonic(KeyEvent.VK_F);
		JMenuItem item;
		URL url;
		filemenu.add(item = new JMenuItem("新建"));
		url = EddyWordPad.class.getResource("resources/new.gif");
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
		         ActionEvent.CTRL_MASK));
		item.setIcon(new ImageIcon(url));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				newDocument();
			}
		});
		
		filemenu.add(item = new JMenuItem("打开"));
		url = EddyWordPad.class.getResource("resources/open.gif");
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		item.setIcon(new ImageIcon(url));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openDocument();
			}
		});
		
		filemenu.add (item = new JMenuItem ("以纯文本打开"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				loadDocument();
			}
		});
		
		filemenu.add (item = new JMenuItem ("保存"));
		url = EddyWordPad.class.getResource("resources/save.gif");
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		item.setIcon(new ImageIcon(url));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().doSaveCommand();
			}
		});
		
		filemenu.add (item = new JMenuItem ("另存为..."));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().savefilename = null;
				getWordPane().doSaveCommand();
			}
		});
		
		filemenu.addSeparator();
		
		filemenu.add (item = new JMenuItem ("页面设置"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				PrinterJob pjob = PrinterJob.getPrinterJob();
				pageformat = pjob.pageDialog(attributes);
			}
		});
		
		filemenu.add (item = new JMenuItem ("打印预览"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().doPrintPreview();
			}
		});
		
		filemenu.add (item = new JMenuItem ("打印..."));
		url = EddyWordPad.class.getResource("resources/print.gif");
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
		         ActionEvent.CTRL_MASK));
		item.setIcon(new ImageIcon(url));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().doPrint();
			}
		});
		
		filemenu.addSeparator();
		filemenu.add (item = new JMenuItem ("退出"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				doExit();
//		TODO		if(doExit()) {
//					System.exit(0);
////				}
//				else
//					return;
			}
		});
		
		return filemenu;
	}
	
	public JMenu createViewMenu() {
		JMenu viewmenu = new JMenu("视图");
		
		JCheckBoxMenuItem item = new JCheckBoxMenuItem("显示地址栏");
		item.setSelected(true);
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				urlBar.setVisible(!urlBar.isVisible());
			}
		});
		viewmenu.add(item);
		
		viewmenu.add(item = new JCheckBoxMenuItem("显示工具条"));
		item.setSelected(true);
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				buttonBar.setVisible(!buttonBar.isVisible());
			}
		});
		
		viewmenu.addSeparator();
		
		ButtonGroup group = new ButtonGroup();
		viewmenu.add(deskTopRadio = new JRadioButtonMenuItem("内部窗体视图"));
		deskTopRadio.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				updateUI();
			}
		});
		group.add(deskTopRadio);
		
		viewmenu.add(tabbedpPaneRadio = new JRadioButtonMenuItem("标签页视图"));
		tabbedpPaneRadio.setSelected(true);
		tabbedpPaneRadio.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				updateUI();
			}
		});
		group.add(tabbedpPaneRadio);
		
		viewmenu.addSeparator();
		
		viewmenu.add(item = new JCheckBoxMenuItem("Set ScrollLayout"));
		item.setSelected(true);
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (tabbedpane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT) {
	               tabbedpane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
	            } else {
	               tabbedpane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
	            }
			}
		});
		
		viewmenu.add(item = new JCheckBoxMenuItem("总在最前"));
		item.setSelected(false);
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getSource();
				WordPadFrame.this.setAlwaysOnTop(item.isSelected());
			}
		});
		
		
		ActionListener placementListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int i = Integer.parseInt(e.getActionCommand());
				tabbedpane.setTabPlacement(i);
			}
		};
		
		viewmenu.addSeparator();
		
		ButtonGroup group2 = new ButtonGroup();
		JRadioButtonMenuItem radioItem;
		String[] placementNames = {"JTabbedPane.TOP", "JTabbedPane.BOTTOM", "JTabbedPane.LEFT", "JTabbedPane.RIGHT"};
		int[] placements = {JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, JTabbedPane.RIGHT};
		for(int i = 0; i < placements.length; i++) {
			viewmenu.add(radioItem = new JRadioButtonMenuItem(placementNames[i]));
			radioItem.setActionCommand(placements[i] + "");
			radioItem.addActionListener(placementListener);
			group2.add(radioItem);
			if(i == 0)
				radioItem.setSelected(true);
		}

		return viewmenu;
	}

	public JMenu createEditorMenu() {
		editormenu = new JMenu("编辑");
		editormenu.setMnemonic(KeyEvent.VK_E);
		JMenuItem item;
		URL url = WordPadPanel.class.getResource("resources/edit_copy.gif");
		editormenu.add(item = new JMenuItem("复制"));
		item.setIcon(new ImageIcon(url));
		item.setMnemonic('c');
	    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getWordPane().getTextPane().copy();
			}
		});
		
		url = WordPadPanel.class.getResource("resources/edit_cut.gif");
		editormenu.add(item = new JMenuItem("剪切"));
		item.setIcon(new ImageIcon(url));
	    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getWordPane().getTextPane().cut();
			}
		});
		
		url = WordPadPanel.class.getResource("resources/edit_paste.gif");
		editormenu.add(item = new JMenuItem("粘贴"));
		item.setIcon(new ImageIcon(url));
	    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK));
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getWordPane().getTextPane().paste();
			}
		});
		
		editormenu.addSeparator();
		
		url = WordPadFrame.class.getResource("resources/edit_undo.gif");
		undoAction = new AbstractAction("回退", new ImageIcon(url)) {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				try {
					wordpane.undoManager.undo();
				} 
			    catch (CannotUndoException ex) {
			       System.err.println("Unable to undo: " + ex);
			    }
			    wordpane.updateUndo();
			}
		 };
		item = editormenu.add(undoAction);
	   item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_MASK));
		
	   url = WordPadFrame.class.getResource("resources/edit_redo.gif");
		redoAction = new AbstractAction("重做", new ImageIcon(url)) {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				try {
					wordpane.undoManager.redo();
				} 
			    catch (CannotUndoException ex) {
			       System.err.println("Unable to undo: " + ex);
			    }
			    wordpane.updateUndo();
			}
		 };
		item = editormenu.add(redoAction);
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_MASK));
		
		editormenu.addSeparator();
		
		url = WordPadPanel.class.getResource("resources/edit_find.gif");
		Action findAction = new AbstractAction("查找...", new ImageIcon(url)) { 
         public void actionPerformed(ActionEvent e) {
        	WordPadPanel wordpane = getWordPane();
            WordPadFrame.this.repaint();
            if (m_findDialog==null)
               m_findDialog = new FindDialog(wordpane, 0);
            else
               m_findDialog.setSelectedIndex(0);
            
            Dimension d1 = m_findDialog.getSize();
            Dimension d2 = WordPadFrame.this.getSize();
            int x = Math.max((d2.width-d1.width)/2, 0);
            int y = Math.max((d2.height-d1.height)/2, 0);
            m_findDialog.setBounds(x + WordPadFrame.this.getX(),
               y + WordPadFrame.this.getY(), d1.width, d1.height);
            
            m_findDialog.show();
         }
      };
      item = editormenu.add(findAction);  
      item.setMnemonic('f');
      item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK));
	   
		Action replaceAction = new AbstractAction("替换...") { 
         public void actionPerformed(ActionEvent e) {
        	WordPadPanel wordpane = getWordPane();
        	WordPadFrame.this.repaint();
            if (m_findDialog==null)
               m_findDialog = new FindDialog(wordpane, 1);
            else
               m_findDialog.setSelectedIndex(0);
            
            Dimension d1 = m_findDialog.getSize();
            Dimension d2 = WordPadFrame.this.getSize();
            int x = Math.max((d2.width-d1.width)/2, 0);
            int y = Math.max((d2.height-d1.height)/2, 0);
            m_findDialog.setBounds(x + WordPadFrame.this.getX(),
               y + WordPadFrame.this.getY(), d1.width, d1.height);
            
            m_findDialog.show();
         }
      };
      item = editormenu.add(replaceAction);  
      item.setMnemonic('r');
      item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK));
	  
      item = new JMenuItem("段落...");
      item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				StyledDocument doc = wordpane.getDocument();
				JTextPane pane = wordpane.getTextPane();
				WordPadFrame.this.repaint();
			    AttributeSet a = doc.getCharacterElement(pane.getCaretPosition()).getAttributes();
			    myparagraphDialog.setAttributes(a);
      	
			    Dimension d1 = myparagraphDialog.getSize();
			    Dimension d2 = WordPadFrame.this.getSize();
			    int x = Math.max((d2.width-d1.width)/2, 0);
			    int y = Math.max((d2.height-d1.height)/2, 0);
			    myparagraphDialog.setBounds(x + WordPadFrame.this.getX(),
			          y + WordPadFrame.this.getY(), d1.width, d1.height);
      	
			    myparagraphDialog.show();
			    if (myparagraphDialog.getOption()==JOptionPane.OK_OPTION) {
			    	 wordpane.setAttributeSet(myparagraphDialog.getAttributes(), true);
			    	 wordpane.showAttributes(pane.getCaretPosition());
			    }
			}
      	});
      	editormenu.add(item); 
      	
      	editormenu.addSeparator();
      	editormenu.add(item = new JMenuItem("显示设置..."));
			item.addActionListener (new ActionListener() {
				public void actionPerformed (ActionEvent e) {
					if(getWordPane().getTextPane() == null) return;
					TextPaneSetDialog paneSetting = new TextPaneSetDialog(WordPadFrame.this, getWordPane().getTextPane());
					int r = paneSetting.showDialog();
					if(r == TextPaneSetDialog.OK) {					
						for(WordPadPanel wordpad : wordpaneVect) {
							wordpad.getTextPane().setBackground(paneSetting.background);
							wordpad.getTextPane().setSelectionColor(paneSetting.selectionColor);
							wordpad.getTextPane().setSelectedTextColor(paneSetting.selectedTextColor);
						}
					}
				}
		});	
      	     
      return editormenu;
	}
	
	public JMenu createColorMenu() {
		JMenu colormenu = new JMenu("颜色");
		JMenuItem item;
		colormenu.add(item = new JMenuItem("Red"));
		item.setIcon(new ColoredBox(Color.red));
		item.addActionListener(new StyledEditorKit.ForegroundAction("set-foreground-red", Color.red));
		
		colormenu.add(item = new JMenuItem("Orange"));
		item.setIcon(new ColoredBox(Color.orange));
		item.addActionListener(new StyledEditorKit.ForegroundAction("set-foreground-orange", Color.orange));
		
		colormenu.add(item = new JMenuItem("Black"));
		item.setIcon(new ColoredBox(Color.black));
		item.addActionListener(new StyledEditorKit.ForegroundAction("set-foreground-black", Color.black));
		
		colormenu.add(item = new JMenuItem("Custom color"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().doColorCommand();
			}
		});
		
		colormenu.add(item = new JMenuItem("Background color"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				Color color = JColorChooser.showDialog(WordPadFrame.this, "Select Color", Color.white);
				if(color == null) return;
				getWordPane().getTextPane().setBackground(color);
			}
		});
		
		colormenu.add(item = new JMenuItem("Select color"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				Color color = JColorChooser.showDialog(WordPadFrame.this, "Select Color", Color.white);
				if(color == null) return;
				getWordPane().getTextPane().setSelectionColor(color);
			}
		});
		
		colormenu.add(item = new JMenuItem("SelectText color"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				Color color = JColorChooser.showDialog(WordPadFrame.this, "Select Color", Color.white);
				if(color == null) return;
				getWordPane().getTextPane().setSelectedTextColor(color);
			}
		});					
		
		return colormenu;
	}
	
	public JMenu createFontMenu() {
		JMenu fontmenu = new JMenu("字体");
		JMenuItem item;
		fontmenu.add (item = new JMenuItem ("12"));
		item.addActionListener (new StyledEditorKit.FontSizeAction ("font-size-12", 12));
		
		fontmenu.add (item = new JMenuItem ("24"));
		item.addActionListener (new StyledEditorKit.FontSizeAction ("font-size-24", 24));
	
		fontmenu.add (item = new JMenuItem ("36"));
		item.addActionListener (new StyledEditorKit.FontSizeAction ("font-size-3", 36));
	

		fontmenu.add (item = new JMenuItem ("Serif"));
		item.setFont (new Font ("Serif", Font.PLAIN, 12));
		item.addActionListener (new StyledEditorKit.FontFamilyAction("font-family-Serif", "Serif"));
		
		fontmenu.add (item = new JMenuItem ("SansSerif"));		
		item.setFont (new Font ("SansSerif", Font.PLAIN, 12));
		item.addActionListener (new StyledEditorKit.FontFamilyAction("font-family-SansSerif", "SansSerif"));
		
		fontmenu.add (item = new JMenuItem ("Monospaced"));
		item.setFont (new Font ("Monospaced", Font.PLAIN, 12));
		item.addActionListener (new StyledEditorKit.FontFamilyAction("font-family-Monospaced", "Monospaced"));
		
		fontmenu.addSeparator();
		
		fontmenu.add (item = new JMenuItem ("Bold"));
		item.setFont (new Font ("Serif", Font.BOLD, 12));
		item.addActionListener (new StyledEditorKit.BoldAction ());
		
		fontmenu.add (item = new JMenuItem ("Italic"));
		item.setFont (new Font ("Serif", Font.ITALIC, 12));
		item.addActionListener (new StyledEditorKit.ItalicAction ());
		
		fontmenu.addSeparator();
		fontmenu.add (item = new JMenuItem ("Font Dialog"));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				getWordPane().doFontCommand();
			}
		});
		
		return fontmenu;
	}
	
	public JMenu createAbortMenu() {
		JMenu abortMenu = new JMenu("帮助");
		JMenuItem item;
		abortMenu.add (item = new JMenuItem ("相关信息..."));
		item.addActionListener (new ActionListener() {
			public void actionPerformed (ActionEvent e) {
				AbortDialog abortdialog = new AbortDialog();
				abortdialog.showDialog();
			}
		});
		
		return abortMenu;
	}
	
	public JToolBar createToolBar() {
		JToolBar jtb = new JToolBar();
		jtb.setLayout(new BorderLayout());
		jtb.setFloatable(true); //可移动的工具条
	   jtb.setBorder(BorderFactory.createEtchedBorder());
		
		buttonBar = new JToolBar();
		buttonBar.setBorder(BorderFactory.createEtchedBorder());
		
		JButton toolButton;
		URL url;
		url = EddyWordPad.class.getResource("resources/new.gif");
		buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
		toolButton.setToolTipText("新建文档");
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				newDocument();
			}
		});
		
		url = EddyWordPad.class.getResource("resources/open.gif");
		buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
		toolButton.setToolTipText("打开文档");
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openDocument();
			}
		});
		
		url = EddyWordPad.class.getResource("resources/save.gif");
		buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
		toolButton.setToolTipText("保存文档");
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getWordPane().doSaveCommand();
			}
		});
		
		url = EddyWordPad.class.getResource("resources/insert.gif");
		buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
		toolButton.setToolTipText("插入图像");
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getWordPane().doInsertCommand();
			}
		});
	
		url = EddyWordPad.class.getResource("resources/forcolor.gif");
		
		buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
		toolButton.setToolTipText("选择颜色");
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				Color color = JColorChooser.showDialog(WordPadFrame.this, "选择颜色", Color.black);
				if(color == null) return;
				MutableAttributeSet atrr = new SimpleAttributeSet();
				StyleConstants.setForeground(atrr, color);
				wordpane.setAttributeSet(atrr, false);
				wordpane.hasSaved = false;
				wordpane.getTextPane().grabFocus();
			}
		});

		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		String[] fontnames = ge.getAvailableFontFamilyNames();
		fontCombo = new JComboBox(fontnames);
		fontCombo.setMaximumSize(fontCombo.getPreferredSize());
		fontCombo.setEditable(true);
		fontCombo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel innerpane = getWordPane();
				String fontname = "";
				fontname = fontCombo.getSelectedItem().toString();
				if(innerpane != null)
					innerpane.m_fontName = fontname;
				MutableAttributeSet attr = new SimpleAttributeSet();
				StyleConstants.setFontFamily(attr, fontname);
				innerpane.setAttributeSet(attr, false);
				innerpane.hasSaved = false;
				innerpane.getTextPane().grabFocus();
			}
		});
		
		buttonBar.add(Box.createHorizontalStrut(10));
		buttonBar.add(fontCombo);
		
		String[] sizes = {"8", "9", "10", "11", "12", "14",
			      "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"};
		sizeCombo = new JComboBox(sizes);
		sizeCombo.setMaximumSize(sizeCombo.getPreferredSize());
		sizeCombo.setEditable(true);
		sizeCombo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				if(wordpane == null)
					return;
				int fontsize = 0;
				fontsize = Integer.parseInt(sizeCombo.getSelectedItem().toString());
				wordpane.m_fontSize = fontsize;
				MutableAttributeSet attr = new SimpleAttributeSet();
				StyleConstants.setFontSize(attr, fontsize);
				wordpane.setAttributeSet(attr, false);
				wordpane.hasSaved = false;
				wordpane.getTextPane().grabFocus();
			}
		});
		buttonBar.add(sizeCombo);
		
		fontDialog = new FontDialog(this, fontnames, sizes);
		
		url = EddyWordPad.class.getResource("resources/font_bold1.gif");
	   ImageIcon img1 = new ImageIcon(url);
	   url = EddyWordPad.class.getResource("resources/font_bold2.gif");
	   ImageIcon img2 = new ImageIcon(url);
	   boldToggleButton = new SmallToggleButton(false, img1, img2,"粗体");
	   boldToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				MutableAttributeSet atrr = new SimpleAttributeSet();
				StyleConstants.setBold(atrr, boldToggleButton.isSelected());
				wordpane.setAttributeSet(atrr, false);
				wordpane.hasSaved = false;
				wordpane.getTextPane().grabFocus();
			}
	   });
	   buttonBar.add(boldToggleButton);
	   
	   url = EddyWordPad.class.getResource("resources/font_italic1.gif");
	   img1 = new ImageIcon(url);
	   url = EddyWordPad.class.getResource("resources/font_italic2.gif");
	   img2 = new ImageIcon(url);
	   italicToggleButton = new SmallToggleButton(false, img1, img2,"斜体");
	   italicToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				MutableAttributeSet atrr = new SimpleAttributeSet();
				StyleConstants.setItalic(atrr, italicToggleButton.isSelected());
				wordpane.setAttributeSet(atrr, true);
				wordpane.hasSaved = false;
				wordpane.getTextPane().grabFocus();
			}
	   });
	   buttonBar.add(italicToggleButton);
	   
	   ActionListener alListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
	   		WordPadPanel wordpane = getWordPane();
				MutableAttributeSet atrr = new SimpleAttributeSet();
				int al = Integer.parseInt(e.getActionCommand());
				StyleConstants.setAlignment(atrr, al);
				wordpane.setAttributeSet(atrr, true);
				wordpane.hasSaved = false;
				wordpane.getTextPane().grabFocus();
	   	}
	   };
	   
	   ButtonGroup algroup = new ButtonGroup();
	   url = EddyWordPad.class.getResource("resources/al_center.gif");
	   img1 = new ImageIcon(url);
	   centerAlignment = new SmallToggleButton(false, img1, img1, "中间对齐");
	   centerAlignment.setActionCommand(StyleConstants.ALIGN_CENTER + "");
	   centerAlignment.addActionListener(alListener);
	   algroup.add(centerAlignment);
	   
	   url = EddyWordPad.class.getResource("resources/al_justify.gif");
	   img1 = new ImageIcon(url);
	   justifyAlignment  = new SmallToggleButton(false, img1, img1, "Justify Alignment");
	  	justifyAlignment.setActionCommand(StyleConstants.ALIGN_JUSTIFIED + "");
	   justifyAlignment.addActionListener(alListener);
	   algroup.add(justifyAlignment);
	   
	   url = EddyWordPad.class.getResource("resources/al_left.gif");
	   img1 = new ImageIcon(url);
	   leftAlignment  = new SmallToggleButton(true, img1, img1, "靠左对齐");
	   leftAlignment.setActionCommand(StyleConstants.ALIGN_LEFT + "");
	   leftAlignment.addActionListener(alListener);
	   algroup.add(leftAlignment);
	   
	   url = EddyWordPad.class.getResource("resources/al_right.gif");
	   img1 = new ImageIcon(url);
	   rightAlignment = new SmallToggleButton(false, img1, img1, "靠右对齐");
	   rightAlignment.setActionCommand(StyleConstants.ALIGN_RIGHT + "");
	   rightAlignment.addActionListener(alListener);
	   algroup.add(rightAlignment);
	   
	   buttonBar.addSeparator();
	   buttonBar.add(centerAlignment);
	   buttonBar.add(justifyAlignment);
	   buttonBar.add(leftAlignment);
	   buttonBar.add(rightAlignment);
	   buttonBar.addSeparator();
	   url = EddyWordPad.class.getResource("resources/print.gif");
	   buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
	   toolButton.setToolTipText("打印文档.");
	   toolButton.addActionListener(new ActionListener() {
		   public void actionPerformed(ActionEvent e) {
			   getWordPane().doPrint();
		   }
	   });
	   
	   buttonBar.addSeparator();
	   url = EddyWordPad.class.getResource("resources/nextPage.gif");
	   buttonBar.add(toolButton = new JButton(new ImageIcon(url)));
	   toolButton.setToolTipText("显示下一屏");
	   toolButton.addActionListener(new ActionListener() {
		   public void actionPerformed(ActionEvent e) {
			   getWordPane().nextPage();
		   }
	   });
	
		urlBar = new JToolBar();
		urlBar.setBorder(BorderFactory.createEtchedBorder());
		
		url = EddyWordPad.class.getResource("resources/back.gif");
		urlBar.add(toolButton = new JButton("Back", new ImageIcon(url)));
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WordPadPanel wordpane = getWordPane();
				if(wordpane.ulrStack.size() <= -1) return;
				try {
					wordpane.ulrStack.pop();
					String urlString = wordpane.ulrStack.peek();
					urlField.setText(urlString);
					wordpane.getTextPane().setPage(urlString);
				}
				catch(Exception ex) {
				}	
			}
		});
		
		urlBar.add(new JLabel(" 地址:"));
				
		urlField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				connect();
			}
		});
		urlBar.add(urlField);
		url = EddyWordPad.class.getResource("resources/goto.gif");
		urlBar.add(toolButton = new JButton("Goto", new ImageIcon(url)));
		toolButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				connect();
			}
		});
		
		//buttonBar.setOrientation(JToolBar.VERTICAL);
		buttonBar.setFloatable(false);
		urlBar.setFloatable(false);
		jtb.add(buttonBar, BorderLayout.NORTH);
		jtb.add(urlBar, BorderLayout.CENTER);
		
		return jtb;
	}
	
	public void newDocument() {
		WordPadPanel pane = new WordPadPanel(WordPadFrame.this);
		wordpaneVect.add(pane);
		
		if(this.tabbedpPaneRadio.isSelected()) {
			tabbedpane.add("New", pane);
			int i = tabbedpane.getTabCount();
			System.out.println(i);
			tabbedpane.setTabComponentAt(i - 1, new ButtonTabComponent(this));
			tabbedpane.setSelectedIndex(i - 1);			
			
		}
		else
		{
			WordPadInternalFrame interfrm = new WordPadInternalFrame(pane, this);
			myDeskPane.add(interfrm);
			interfrm.show();
			try {
				interfrm.setSelected(true);
			}catch(Exception ex) {}
		}
		pane.doNewCommand();
	}
	
	public void openDocument() {
		Thread thread = new Thread() {
			public void run() {
				WordPadPanel pane = new WordPadPanel(WordPadFrame.this);
				if(!pane.doOpenCommand(null)) return;
				wordpaneVect.add(pane);
				
				if(tabbedpPaneRadio.isSelected()) {
					tabbedpane.add(pane.getTitle(),pane);
					int i = tabbedpane.getTabCount();
					tabbedpane.setTabComponentAt(i - 1, new ButtonTabComponent(WordPadFrame.this));
					tabbedpane.setSelectedIndex(i - 1);	
				}
				else
				{
					WordPadInternalFrame interfrm = new WordPadInternalFrame(pane, WordPadFrame.this);
					myDeskPane.add(interfrm);
					interfrm.show();
				}
			}
		};
		thread.start();
	}
	
	public void loadDocument() {
		Thread thread = new Thread() {
			public void run() {
				WordPadPanel pane = new WordPadPanel(WordPadFrame.this);
				if(!pane.doLoadCommand(null)) return;
				wordpaneVect.add(pane);
				updateUI();
			}
		};
		thread.start();
	}
	
	public void connect() {
		Thread thread = new Thread() {
			public void run() {
				newDocument();
				WordPadPanel wordpane = getWordPane();
				wordpane.getTextPane().setEditable(false);
				try {
					wordpane.ulrStack.push(urlField.getText());					
					wordpane.getTextPane().setPage(urlField.getText());
					wordpane.setStatus(urlField.getText());
				} catch (IOException e1) {
					wordpane.getTextPane().setText(e1.toString());
				}
			}
		};
		thread.start();
	}
	
	public boolean doExit() {
		boolean canClose = true;
		if(this.tabbedpPaneRadio.isSelected()) {
			for(WordPadPanel pane:wordpaneVect) {
				canClose = pane.doCloseCommand2();
				if(!canClose)
					break;
				tabbedpane.remove(pane);
				
			}
		}
		else if(this.deskTopRadio.isSelected()) {
			JInternalFrame[] frames = myDeskPane.getAllFrames();
			for(JInternalFrame interFrame : frames ) {
				WordPadInternalFrame frame = (WordPadInternalFrame) interFrame;
				canClose = frame.getWordPadPanel().doCloseCommand2();
				if(!canClose)
					break;
				
				frame.setVisible(false);
				myDeskPane.remove(frame);
			}
		}
		
		if(canClose) {
			wordpaneVect.clear();
			return true;
		}	
		
		return false;
	}

	public WordPadPanel getWordPane() {
		WordPadPanel pane;
		if(tabbedpPaneRadio.isSelected())
			pane = (WordPadPanel) tabbedpane.getSelectedComponent();
		else {
			WordPadInternalFrame selectFrame = (WordPadInternalFrame) myDeskPane.getSelectedFrame();
			pane = selectFrame.getWordPadPanel();
		}
		return pane;
	}
	
	public void updateUI() {
		if(tabbedpPaneRadio.isSelected()) {
			this.getContentPane().remove(myDeskPane);
			tabbedpane.removeAll();
			int i = 0;
			for(WordPadPanel pane:wordpaneVect) {
				tabbedpane.add(pane.getTitle(),pane);
				tabbedpane.setTabComponentAt(i++, new ButtonTabComponent(this));
			}
			this.getContentPane().add(tabbedpane, BorderLayout.CENTER);
		}
		
		else if(deskTopRadio.isSelected()) {
			myDeskPane.removeAll();
			this.getContentPane().remove(tabbedpane);
			for(WordPadPanel pane:wordpaneVect) {
				WordPadInternalFrame interfrm = new WordPadInternalFrame(pane, this);
				myDeskPane.add(interfrm);
				interfrm.show();
			}
			this.getContentPane().add(myDeskPane, BorderLayout.CENTER);
		}
		
		this.repaint();
  		this.validate();
	}
	
	public HashPrintRequestAttributeSet getAttributes() {
		return attributes;
	}
	
	public void setAttributes(HashPrintRequestAttributeSet att) {
		this.attributes = att;
	}
	
	public JDesktopPane getDeskTopPane() {
		return this.myDeskPane;
	}
	
	public JTabbedPane getJTabbedPane() {
		return this.tabbedpane;
	}
	
	public JMenu getlafmenu() {
		return lafmenu;
	}
	
	public JMenu geteditmenu() {
		return editormenu;
	}
	
	private JMenu editormenu;
	private JMenu lafmenu;
	protected JRadioButtonMenuItem deskTopRadio;
	protected JRadioButtonMenuItem tabbedpPaneRadio;
	public int index = 0;
	public HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
	public PageFormat pageformat;
	protected Vector<WordPadPanel> wordpaneVect = new Vector<WordPadPanel>();
	JToolBar urlBar;
	JToolBar buttonBar;
	JCheckBoxMenuItem showURLitem;
	protected ParagraphDialog myparagraphDialog;
	protected JDesktopPane myDeskPane;
	protected JTabbedPane tabbedpane;
	final JTextField urlField = new JTextField(30);
	protected FindDialog m_findDialog;
	protected JComboBox fontCombo;
	protected JComboBox sizeCombo;
	protected Action undoAction;
	protected Action redoAction;
	protected FontDialog fontDialog;
	protected SmallToggleButton boldToggleButton;
	protected SmallToggleButton italicToggleButton;
	protected SmallToggleButton centerAlignment;
	protected SmallToggleButton leftAlignment;
	protected SmallToggleButton rightAlignment;
	protected SmallToggleButton justifyAlignment;
}
